package ch5;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 通用任务执行器
 * 生产者只需要调用TaskRunner.submit(Runnable)提交一个任务，该任务即可被TaskRunner执行
 * 即一个TaskRunner实例可以运行多种不同的任务
 */

public class TaskRunner {
    protected final BlockingQueue<Runnable> channel;
    protected volatile Thread workerThread;

    public TaskRunner(BlockingQueue<Runnable> queue) {
        this.channel = queue;
        workerThread = new WorkerThread();
    }

    public TaskRunner() {
        this(new LinkedBlockingDeque<Runnable>());
    }

    public void init() {
        final Thread t = workerThread;
        if (null != t) {
            t.start();
        }
    }

    // 生产者通过submit向TaskRunner提交任务
    public void submit(Runnable task) throws InterruptedException {
       channel.put(task);
    }

    class WorkerThread extends Thread {
        @Override
        public void run() {
           Runnable task = null;
           try {
               for (;;) {
                   task = channel.take();
                   try {
                       task.run();
                   } catch (Throwable e) {
                       e.printStackTrace();
                   }
               }
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
        }
    }
}
